package com.jszc.lottery.common.datatest;

import java.util.regex.Pattern;

/**
 * Created by Administrator on 2015/10/21.
 */
public class ValidateUtil {

    /**
     * 验证字符串类型，多种类型可以用"|"复合使用StringType
     * @param strSource
     * @param stringType
     * @return
     */
    public static boolean ValidateStringType(String strSource, StringType stringType){
        String legalString = "_\\-\\*\\%\\$#@!\\^\\(\\)\\?\":;\\.，‘’【】｛｝《》；：！？“”。\\{\\[\\]\\|\\\\";//无法使用Regex.Escape
        return validateStringType(strSource, stringType, legalString);
    }

    /**
     *  验证字符串类型，多种类型可以用"|"复合使用StringType,StringType为LegalChar使用的字符,必要时可以自己修改legalString
     * @param strSource
     * @param stringType
     * @param legalString
     * @return
     */
    public static boolean validateStringType(String strSource, StringType stringType, String legalString){
        if (StrUtil.isTEpt(strSource))
        {
            return false;
        }
        strSource = strSource.trim();
        String pattern = "^(";
        if ((stringType.getCode() | ValidateUtil.StringType.Chinese.getCode()) == stringType.getCode())
        {
            pattern += "|[\\u4E00-\\u9FA5]";
        }
        if ((stringType.getCode() | ValidateUtil.StringType.Numeric.getCode()) == stringType.getCode())
        {
            pattern += "|[0-9]";
        }
        if ((stringType.getCode() | StringType.Letter.getCode()) == stringType.getCode())
        {
            pattern += "|[A-Za-z]";
        }
        if ((stringType.getCode() | StringType.LegalSymbol.getCode()) == stringType.getCode())
        {
            pattern += "|[" + legalString + "]";
        }
        pattern += ")+$";
        return validateByPattern(strSource, pattern);
    }

    /**
     * 用正则验证
     * @param strSource
     * @param pattern
     * @return
     */
    public static Boolean validateByPattern(String strSource, String pattern){
        if (StrUtil.isTEpt(strSource))
        {
            return false;
        }
        strSource = strSource.trim();
        if(Pattern.compile(pattern).matcher(strSource).matches()){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 待字符串类型枚举
     */
    public enum StringType
    {
        Chinese(1),Letter(2),Numeric(4),LegalSymbol(8);

        private int code;
        public int getCode(){
            return code;
        }

        private StringType(int code){
            this.code = code;
        }

        @Override
        public String toString() {
            return String.valueOf(this.code);
        }
    }
}


